package com.longrise.android.byjk.plugins.customerservice;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.common.utils.FolderConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.permission.PermissionUtil;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.NetUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.widget.view.BaseFrameView;
import com.longrise.android.ui.dialog.ActionSheetDialog;

import java.io.File;


/**
 * Created by callxkj on 16/6/30.
 * 客服
 */
public class CustomerServicesActivity extends BaseActivity implements BaseFrameView.ReloadListener {

    private static final String TAG = "CustomerServicesActivity";
    private static int mMode;
    private static final int LOW_EDITION = 1;
    private static final int HIGH_EDITION = 2;
    private static final int CAMERA = 3;
    private static final int GALLERY = 4;

    private WebView mWv;
    private BaseFrameView mBaseFrameView;
    private boolean loadError;
    private String mUrl;

    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mFilePathCallback;
    private String mCameraPhotoPath;
    private Toolbar mToolbar;
    private TextView mTitletv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customerservice);
        initView();
    }

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_customerservice;
    }

    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("");
        mTitletv = (TextView) findViewById(R.id.bb_toolbar_middle_title);
        mTitletv.setVisibility(View.VISIBLE);
        mTitletv.setText(AppUtil.getString(R.string.bbkf));
        mWv = (WebView) findViewById(R.id.customerservice_webview);
        mBaseFrameView = (BaseFrameView) findViewById(R.id.customerservice_loading);
        initData();
        initEvent();
    }

    private void initData() {

        WebSettings webSettings = mWv.getSettings();

        webSettings.setLoadWithOverviewMode(true);

        // 设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        // 设置可以访问文件
        webSettings.setAllowFileAccess(true);

        webSettings.setLoadsImagesAutomatically(true);

        webSettings.setDomStorageEnabled(true);

        webSettings.setAppCacheMaxSize(1024*1024*8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();

        webSettings.setAppCachePath(appCachePath);
        webSettings.setAllowFileAccess(true);

        webSettings.setAppCacheEnabled(true);

        mUrl = getUrl();

        mWv.setWebViewClient(new CustomerServicesClient());

        mWv.setWebChromeClient(new DWebChromeClient());

        if (checkNetwork()) {
            // 加载需要显示的网页
            mWv.loadUrl(mUrl);
        }
    }

    private void initEvent() {
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBaseFrameView.setOnReloadListener(this);
    }

    /**
     * 客服地址
     *
     * @return
     */
    private String getUrl() {
        String BASE_URL = "https://a1.7x24cc.com/phone_webChat.html?accountId=N000000007880&chatId=yxy-db745860-4736-11e6-993a-d3d7ccb9900e";
        String url = null;
        String sfzh = UserInfor.getInstance().getUsersfzh();
        if (TextUtils.isEmpty(sfzh)) {
            url = BASE_URL;
        } else {
            url = BASE_URL + "&customerId=" + sfzh;
        }
        return url;
    }


    @Override
    public void onReload(View v) {
        if (checkNetwork()) {
            PrintLog.d(TAG, "onReload");
            loadError = false;
            mWv.loadUrl(mUrl);
        }
    }


    private class CustomerServicesClient extends WebViewClient {

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            PrintLog.d(TAG, "onReceivedError");
            loadError = true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            PrintLog.d(TAG, "url:" + url);
            PrintLog.d(TAG, "murl:" + mUrl);
            super.onPageFinished(view, url);
            if (loadError) {
                mBaseFrameView.setVisibility(View.VISIBLE);
                mWv.setVisibility(View.GONE);
                mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
            } else {
                if (!(TextUtils.isEmpty(mUrl)) && mUrl.equals(url)) {
                    PrintLog.d(TAG, "onPageFinished");
                    mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
                    mBaseFrameView.setVisibility(View.GONE);
                    mWv.setVisibility(View.VISIBLE);
                }
            }
            mUrl = url;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;

        }
    }

    /**
     * 检查是否有网络
     *
     * @return
     */
    private boolean checkNetwork() {
        if (!NetUtil.checkNetEnable()) {
            mBaseFrameView.setVisibility(View.VISIBLE);
            mWv.setVisibility(View.GONE);
            mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
            return false;
        } else {
            return true;
        }

    }


    private class DWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title) && title.toLowerCase().contains("error")) {
                loadError = true;
            }
        }

        // android 5.0
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            mMode = HIGH_EDITION;
            mFilePathCallback = filePathCallback;
            checkPermission();
            return true;
        }

        //3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mMode = LOW_EDITION;
            mUploadMessage = uploadMsg;
            checkPermission();
        }

        // 3.0
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            mMode = LOW_EDITION;
            mUploadMessage = uploadMsg;
            checkPermission();
        }

        //4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mMode = LOW_EDITION;
            mUploadMessage = uploadMsg;
            checkPermission();
        }

    }

    private void checkPermission() {
        PermissionUtil.getInstance().requestPermission(this, PermissionUtil.Permission.CAMERA,
                getString(R.string.camera_permission), getString(R.string.camera_permission_hint)
                , new PermissionUtil.PermissionCallBack() {
                    @Override
                    public void onSuccess() {
                        showSelectDialog();
                    }

                    @Override
                    public void onDenied() {
                        clear();
                    }
                });
    }

    private void showSelectDialog() {
        new ActionSheetDialog(CustomerServicesActivity.this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent intent = new Intent();
                                // 指定开启系统相机的Action
                                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                                intent.addCategory(Intent.CATEGORY_DEFAULT);

                                // 根据文件地址创建文件
                                File file = new File(FolderConstants.CSPIC_DIR + "/cs.jpg");
                                File parent = file.getParentFile();
                                if (!parent.exists()) {
                                    parent.mkdirs();
                                }
                                if (file.exists()) {
                                    file.delete();
                                }

                                // 把文件地址转换成Uri格式
                               // Uri uri = Uri.fromFile(file);

                                // 兼容7.0
                                Uri imageUri = FileProvider.getUriForFile(CustomerServicesActivity.this
                                        ,FolderConstants.FILE_PROVIDER,file);

                                // 设置系统相机拍摄照片完成后图片文件的存放地址
                                //intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                                startActivityForResult(intent, CAMERA);

                            }
                        })
                .addSheetItem("相册", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent intent = new Intent(Intent.ACTION_PICK, null);
                                intent.setDataAndType(
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                startActivityForResult(intent, GALLERY);
                            }
                        })
                .setOnCancelListener(new ActionSheetDialog.OncancelListener() {
                    @Override
                    public void onCancel() {
                        clear();
                    }
                }).show();
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            File file = new File(FolderConstants.CSPIC_DIR + "/cs.jpg");
            if (requestCode == CAMERA && file.exists()) {
                Uri uri = Uri.fromFile(file);
                if (mMode == HIGH_EDITION) {
                    Uri[] results = new Uri[]{uri};
                    mFilePathCallback.onReceiveValue(results);

                } else if (mMode == LOW_EDITION) {
                    mUploadMessage.onReceiveValue(uri);
                } else {
                    clear();
                }

            } else {
                if (requestCode == GALLERY && data != null) {

                    String path = null;
                    if ("file".equalsIgnoreCase(data.getData().getScheme())) {
                        path = data.getDataString();
                        PrintLog.d(TAG, "path1:" + path);
                    } else {
                        Uri uri = data.getData();
                        path = getPath(CustomerServicesActivity.this, uri);
                        // path = getAbsolutePath(CustomerServicesActivity.this, uri);
                        PrintLog.d(TAG, "path2:" + path);
                        if ((!TextUtils.isEmpty(path)) && (!path.contains("file"))) {
                            path = "file://" + path;
                            PrintLog.d(TAG, "path3:" + path);
                        }

                    }

                    Uri uri = Uri.parse(path);

                    if (mMode == HIGH_EDITION) {
                        Uri[] results = new Uri[]{uri};
                        mFilePathCallback.onReceiveValue(results);
                    } else if (mMode == LOW_EDITION) {
                        mUploadMessage.onReceiveValue(uri);
                    } else {
                        clear();
                    }
                } else {
                    clear();
                }
            }
        } else {
            clear();
        }
    }

    public String getAbsolutePath(final Context context,
                                  final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA},
                    null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(
                            MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    //  --------------------getPath- start -----------

    public String getPath(final Context context, final Uri uri) {

        // DocumentProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {

            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static String getDataColumn(Context context, Uri uri,
                                       String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }


    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }


    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }


    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri
                .getAuthority());
    }

    //  --------------------getPath- end -----------

    private void clear() {
        if (mMode == HIGH_EDITION && mFilePathCallback != null) {
            mFilePathCallback.onReceiveValue(null);
            mFilePathCallback = null;
        } else if (mMode == LOW_EDITION && mUploadMessage != null) {
            mUploadMessage.onReceiveValue(null);
            mUploadMessage = null;
        }
    }

    @Override
    protected void onDestroy() {
        mWv.destroy();
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
